package com.zhangpan.uaa.service;


import com.zhangpan.uaa.dao.UserDao;
import com.zhangpan.uaa.entity.UserDto;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.security.auth.login.LoginException;
import java.util.List;

@Service
public class SpringDataUserDetailsService implements UserDetailsService {

    @Bean
    public PasswordEncoder passwordEncoder() {

        return new BCryptPasswordEncoder();
    }

    @Autowired
    UserDao userDao;

    @SneakyThrows
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //登录账号
        System.out.println("username = " + username);
        //根据账号去数据库查询
        UserDto userDto = userDao.getUserByUsername(username);
        if (userDto == null){

            throw new LoginException("用户名或密码错误");
        }

        //查询用户权限
        List<String> permissions = userDao.findPermissionByUserId(userDto.getId());
        String[] perarry = new String[permissions.size()];
        permissions.toArray(perarry);


        //这里暂时使用静态资源
        UserDetails userDetails = User.withUsername(userDto.getUsername()).password(passwordEncoder().encode(userDto.getPassword())).authorities(perarry).build();

        return userDetails;
    }
}
